import React, { useState, useEffect } from 'react';
import { Divider, Modal, Descriptions, Button, Popconfirm } from 'antd';
// @ts-ignore
import QRCode from 'qrcode.react';
import {
  getRentDetailByRentOrderId,
  getOrderRentDetail,
  getRentSettleDetail,
  rentPay,
  updateSettleStatus,
} from '@/services/order/api';
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import { print, showMsg, isNull, isExits } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import { useModel } from 'umi';
import './style.less';

const Rent: React.FC<any> = (props) => {
  const {
    record = {},
    orderRentData,
    handleRent,
    rentType,
    handleModalVisible,
    optCallback,
    title,
    printNow,
    setPrintNow,
    isPrint = false, // 打开弹窗直接打印
    printCallBack, // 用于初始化打印状态
    cancelOrder,
  } = props;

  const { initialState } = useModel('@@initialState');

  const [loading, setLoading] = useState(false);

  // 物品列表
  const [goodsList, setGoodsList] = useState<any[]>([]);
  // 租赁详情
  const [rentDetail, setRentDetail] = useState<any>({});
  // 结算详情
  const [settleDetail, setSettleDetail] = useState<any>({});

  // 商品数量
  const [goodsNums, setGoodsNums] = useState<number>(0);

  // 患者信息
  const [patientInfo, setPatientInfo] = useState<any>(record || {});

  // 提交状态
  const [submitLoading, setSubmitLoading] = useState<boolean>(false);

  // 是否弹出打印窗口
  const [printing, setPrinting] = useState(false);

  const columns: ProColumns<any>[] = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 200,
    },
    {
      title: '登记时间',
      dataIndex: 'register_time',
      width: 170,
    },
    {
      title: '租赁周期',
      dataIndex: 'lease_cycle',
      width: 80,
      valueType: 'select',
      valueEnum: {
        H: '按小时',
        D: '按天',
      },
    },
    {
      title: '周期长度',
      dataIndex: 'cycle_num',
      width: 80,
      align: 'right',
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      valueType: 'money',
      align: 'right',
      width: 80,
    },
    {
      title: '数量',
      dataIndex: 'goods_num',
      align: 'right',
      width: 70,
    },
    {
      title: '价格',
      dataIndex: 'goods_total_price',
      valueType: 'money',
      align: 'right',
      width: 80,
    },
    {
      title: '记录状态',
      dataIndex: 'status',
      width: 80,
      align: 'right',
      valueEnum: {
        N: '正常',
        D: '作废'
      }
    },
  ];

  useEffect(() => {
    const { rent_order_id, sett_id } = record;
    // 按单据展示-查看
    if (rent_order_id) {
      getRentDetail();
    } else if (sett_id) {
      getDetailBySettle();
    }
  }, [record]);

  // 按租赁订单id 查看租赁详情
  const getRentDetail = async () => {
    try {
      const data = await getRentDetailByRentOrderId(record.rent_order_id);
      setRentDetail(data);
      const { order_rent_sett } = data;
      const settDetail = {
        rent_order_id: data.rent_order_id,
        sett_id: data.rent_order_id,
        create_date: `${data.create_date} ${data.create_time}`,
        sett_time: order_rent_sett?.sett_time,
        sett_price: data.sett_price,
        create_person: `${data.create_dept_name}/${data.create_user_name}`,
        modify_user_name: data.modify_user_name,
        pay_qr_code_url: order_rent_sett?.pay_qr_code_url,
        sett_status: data.sett_status,
        manager_flag: order_rent_sett?.manager_flag,
        manager_entity: order_rent_sett?.manager_entity,
        create_dept_name: data.create_dept_name,
      }
      setSettleDetail(settDetail);
      // setSettleDetail(Object.assign({}, data, data.order_rent_sett));
      // setSettleDetail(Object.assign({}, data));
      
      // 合并支付订单，需要根据sett_id 查询物品列表
      if (data.sett_flag === 'M') {
        const { sett_id } = data.order_rent_sett;
        const data2 = await getOrderRentDetail({
          current: 1,
          pageSize: 10000,
          sett_id
        })
        setGoodsList(data2.record_list);
        // 商品数
        let nums = 0;
        data2.record_list.forEach((item) => {
          if (item.status !== 'D') {
            nums += item.goods_num;
          }
        });
        setGoodsNums(nums);
      } else {
        setGoodsList(data.detail_list);
        // 商品数
        let nums = 0;
        data.detail_list.forEach((item) => {
          if (item.status !== 'D') {
            nums += item.goods_num;
          }
        });
        setGoodsNums(nums);
      }

      if (printNow) {
        setTimeout(() => {
          print(document.querySelector('.rent-order-modal .ant-modal-body'), {
            size: 'portrait'
          });
        })
      }
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  // 按结算单查询详情
  const getDetailBySettle = async () => {
    try {
      // 结算详情
      const data = await getRentSettleDetail(record.sett_id);
      const settDetail = {
        sett_id: data.sett_id,
        create_date: `${data.create_date} ${data.create_time}`,
        sett_time: data.sett_time,
        sett_price: data.sett_price,
        create_person: `${data.create_dept_name}/${data.create_user_name}`,
        modify_user_name: data.modify_user_name,
        pay_qr_code_url: data.pay_qr_code_url,
        sett_status: data.sett_status,
        manager_flag: data.manager_flag,
        manager_entity: data.manager_entity
      }
      setSettleDetail(settDetail);

      // setSettleDetail(data);
      // 物品列表
       const itemData = await getOrderRentDetail({
        current: 1,
        pageSize: 10000,
        sett_id: record.sett_id
       });
       setGoodsList(itemData.record_list);
       // 商品数
       let nums = 0;
       itemData?.record_list?.forEach((item) => {
        if (item.status !== 'D') {
          nums += item.goods_num;
        }
       });
       setGoodsNums(nums);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  const init = async () => {
    const { rent_order_id, sett_id } = record;
    // 按住院号展示 - 详情 - 结算详情
    setLoading(true);
    if (sett_id) {
      await getDetailBySettle();
    } else if (rent_order_id) {
      await getRentDetail();
    }
    setLoading(false);
  }

  const printPage = () => {
    setPrinting(true);
    setTimeout(() => {
      print(document.querySelector('.rent-order-modal .ant-modal-body'), {
        size: 'portrait'
      });
      setTimeout(() => {
        setPrinting(false);
      }, 5000);
    }, 500);
  }

  useEffect(() => {
    // 现结租赁
    if (rentType === 2) {
      setPatientInfo(orderRentData);
      const list = orderRentData?.detail_list.map((item, index) => {
        return {
          ...item,
          detail_id: index,
        };
      });
      setGoodsList(list);
      let nums = 0;
      let price = 0;
      list?.forEach((item) => {
        price += parseFloat(item.goods_total_price);
        nums += item.goods_num;
      });
      console.log('price', price);
      setGoodsNums(nums);
      setSettleDetail({
        sett_id: '',
        create_date: '',
        sett_price: parseFloat(price).toFixed(2),
        create_person: `${initialState?.currentUser?.dept_name}/${initialState?.currentUser?.oper_name}`,
        modify_user_name: '',
        pay_qr_code_url: '',
        sett_status: 'U',
        manager_flag: null,
        manager_entity: null
      });
    }
    console.log('isPrint', isPrint)
      if (isPrint) {
        printPage();
        printCallBack?.(false);
      }
  }, [rentType]);

  // 获取结算状态
  const getSettleStatus = () => {
    // 合并支付状态
    if (rentDetail?.sett_flag === 'M' && rentDetail.admission_status === 'I' && settleDetail.sett_status !== 'P') {
      return '合并支付中(如需单独支付，请先取消合并支付订单)';
    }

    return settleDetail.sett_status === 'U'
      ? '未结算'
      : settleDetail.sett_status === 'P'
      ? '已结算' : settleDetail.sett_status === 'W' ? '待结算' : '结算中';
  };

  // 是否可支付
  const canPay = () => {
    // 合并支付单和作废单，不允许发起支付
    if (rentDetail?.sett_flag === 'M' || rentDetail.status === 'D') {
      return false;
    }
    return ['U'].includes(settleDetail.sett_status) && settleDetail.manager_flag !== 'Y';
  };

  const showEwm = ['G', 'W'].includes(settleDetail.sett_status) && !isNull(settleDetail.pay_qr_code_url);

  console.log('rentType', rentType, settleDetail)
  return (
    <Modal
      width="90%"
      title={title || '查看订单'}
      bodyStyle={{ height: window.innerHeight - 185, overflowY: 'auto' }}
      className="rent-order-modal"
      maskClosable={false}
      confirmLoading={loading}
      onCancel={() => {
        setPrintNow?.(false)
        handleModalVisible(false)
      }}
      footer={[
        <Button key="back" onClick={() => {
            handleModalVisible(false);
            setPrintNow?.(false)
          }}
        >
          关闭
        </Button>,

        (rentType === 1 && settleDetail.manager_flag === 'Y') &&
        <Popconfirm 
          placement="topRight"
          key="cancel"
          title={record.manager_flag === 'Y' ? '该笔订单已经通过出院办结发起结算，是否确认取消？' : ''}
          onConfirm={() => {
            cancelOrder(() => {
              console.log('rentType', rentType)
              if (rentType === 1) {
                getRentDetail();
              }
            });
          }}
          okText="确认取消"
          disabled={record.manager_flag !== 'Y'}
          cancelText="再想想">
            <Button style={{ marginLeft: 10 }} onClick={() => {
              if (record.manager_flag !== 'Y') {
                cancelOrder(() => {
                  // if (rentType === 1) {
                    getRentDetail();
                  // }
                });
              }
            }}>取消</Button>
        </Popconfirm>,

        ['G'].includes(settleDetail.sett_status) &&
        <Button
          key="refresh"
          loading={loading}
          type="primary"
          onClick={() => {
            init();
          }}
        >
          刷新
        </Button>,

        canPay() && (
          <PermissionControl key="view" action_id="400402013">
            <Button
              loading={submitLoading}
              key="pay"
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={async () => {
                try {
                  let data = null;
                  if (submitLoading) {
                    return;
                  }
                  if (record.rent_order_id) {
                    setSubmitLoading(true);
                    await rentPay(record.rent_order_id);
                    data = await getRentDetailByRentOrderId(record.rent_order_id);
                    optCallback?.(data.order_rent_sett);
                    setSubmitLoading(false);
                  } else {
                    // 现结租赁支付
                    // eslint-disable-next-line no-lonely-if
                    if (rentType === 2) {
                      setSubmitLoading(true);
                      const data = await handleRent(orderRentData);
                      if (data) {
                        optCallback?.(
                          Object.assign({}, data, { pay_valid_time: data.order_rent_sett.pay_valid_time, rentType: 2 }),
                        );
                      }
                      setSubmitLoading(false);
                    } else {
                      setSubmitLoading(true);
                      await updateSettleStatus({
                        sett_id: record.sett_id || settleDetail.sett_id,
                        sett_status: 'G',
                      });
                      data = await getRentSettleDetail(record.sett_id);
                      optCallback?.(data);
                      setSubmitLoading(false);
                    }
                  }
                } catch (error) {
                  console.log(error);
                  setSubmitLoading(false);
                  showMsg(error?.data?.errmsg);
                }
              }}
            >
              发起支付
            </Button>
          </PermissionControl>
        ),
        (showEwm || settleDetail.sett_status === 'P') &&
        <Button
          key="print"
          type="primary"
          onClick={printPage}
        >
          打印结算单
        </Button>
      ]}
      visible
    >
      <div className="dialog">
        <div className='print_yes print_title'>缴费单</div>
        <Divider className='print_yes' style={{ paddingBottom: 15 }} />
        <div className="common_title">1.患者信息</div>
        <Divider style={{ margin: '10px 0' }} />
        <Descriptions column={printing ? 4 : 3}>
          <Descriptions.Item label="住院号/身份证号" span={printing ? 2 : 1}>
            {patientInfo.admission_num}{patientInfo.admission_num && patientInfo.identity_no ? ' / ' : ''}{patientInfo.identity_no}
          </Descriptions.Item>
          <Descriptions.Item label="患者姓名">{patientInfo.patient_name}</Descriptions.Item>
          <Descriptions.Item label="归属科室">
            {patientInfo.create_dept_name ||
              patientInfo.admission_dept_name ||
              settleDetail.create_dept_name}
          </Descriptions.Item>
        </Descriptions>

        <div className="common_title" style={{ marginTop: 10 }}>
          2.物品信息
        </div>
        <Divider />
        <ProTable<any>
          rowKey="detail_id"
          columns={columns}
          style={{ height: 'auto' }}
          className="goods-list-table"
          rowClassName={(record) => {
            console.log('rowClassName', record.id)
            if (record.rent_order_id === settleDetail.rent_order_id && rentDetail?.sett_flag === 'M') {
              return 'new-add';
            }
            return ''
          }}
          pagination={false}
          search={false}
          dataSource={goodsList}
          options={false}
          bordered
        />

        <div className="common_title" style={{ marginTop: 10 }}>
          3.结算信息
        </div>
        <Divider style={{ margin: '10px 0' }} />

        <Descriptions column={showEwm ? 5 : 3}>
        <Descriptions.Item span={showEwm ? 4 : 3} className='noBottom'>
          <Descriptions column={showEwm ? 2: 3}>
            <Descriptions.Item label="结算单号">
              {settleDetail.sett_id && settleDetail.sett_status !=='U' ? settleDetail.sett_id : '-'}
            </Descriptions.Item>
            {
              settleDetail.create_date &&
              <Descriptions.Item label="创建时间">
                {settleDetail.create_date}
              </Descriptions.Item>
            }
            <Descriptions.Item label="物品数量">
              <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{goodsNums}</span>（件）
            </Descriptions.Item>
            <Descriptions.Item label="结算价格">
              <div><span style={{ color: '#F5232D', fontWeight: 'bold' }}>{settleDetail.sett_price}</span>
              （元）
              {settleDetail.manager_flag === 'Y' && '（通过出院办结合并支付）'}</div>
            </Descriptions.Item>
            {
              // !printing &&
              <>
                <Descriptions.Item label="订单创建人">
                  {settleDetail.create_person}
                </Descriptions.Item>
                <Descriptions.Item label="订单修改人">
                  {settleDetail.modify_user_name || '无'}
                </Descriptions.Item>
              </>
            }
            
            
            <Descriptions.Item label="订单状态">{getSettleStatus()}</Descriptions.Item>
          </Descriptions>
          </Descriptions.Item>
          {
            showEwm &&
            <Descriptions.Item className='noBottom'>
              <Descriptions column={1}>
                <Descriptions.Item label="扫码支付">
                  <QRCode
                    value={settleDetail?.pay_qr_code_url || ''}
                    size={80}
                    fgColor="#000"
                    renderAs="svg"
                  />
                </Descriptions.Item>
              </Descriptions>
            </Descriptions.Item>
          }
        </Descriptions>
      </div>
    </Modal>
  );
};
export default Rent;
